昨天我們使用了 Array 來實作佇列,今天我們要來用鏈結串列來實施佇列。
我們使用單向鏈結串列(Single Linked List)來實作,在 Linked List 佇列實作中,最重要的就是要討論佇列為空以及佇列非空的情況了。
環狀鏈結串列(Circular Linked List)與單向鏈結串列最大的不同就在於:串列尾端元素不會指向 null,而是指向開頭元素,因此只需要一個 rear 指標即可,不須 front 和 rear 兩個指標。
#include <iostream>
#include <limits.h>
using namespace std;
typedef struct node{
int data;
struct node* next;
}node_t;
class Queue{
// Single LL
private:
node_t* front;
node_t* rear;
public:
Queue();
void enqueue(int item);
int dequeue();
};
Queue::Queue(){
front = nullptr;
rear = nullptr;
}
void Queue::enqueue(int item){
node_t* newNode = new node_t;
newNode->data = item;
newNode->next = nullptr;
if(front == nullptr){
front = newNode;
}else{
rear->next = newNode;
}
rear = newNode;
}
int Queue::dequeue(){
if(front == nullptr){
cout << "dequeue fail." << endl;
return INT_MIN;
}
node_t* p = front;
int temp = p->data;
front = p->next;
if(front == nullptr) rear = nullptr; // now queue is empty
delete p;
return temp;
}
#include <iostream>
#include <limits.h>
using namespace std;
typedef struct node{
int data;
struct node* next;
}node_t;
class Queue{
// Circular LL
private:
node_t* rear;
public:
Queue();
void enqueue(int item);
int dequeue();
};
Queue::Queue(){
rear = nullptr;
}
void Queue::enqueue(int item){
node_t* newNode = new node_t;
newNode->data = item;
if(rear == nullptr){
newNode->next = newNode;
}else{
newNode->next = rear->next;
rear->next = newNode;
}
rear = newNode;
}
int Queue::dequeue(){
if(rear == nullptr){
cout << "dequeue fail." << endl;
return INT_MIN;
}
node_t* p = rear->next;
int temp = p->data;
if(p->next == p) rear = nullptr; // now queue is empty
else{
rear->next = p->next;
}
delete p;
return temp;
}